package net.easyjava.tools.file;



import net.easyjava.tools.BaseTools;
import net.easyjava.tools.lang.StringTools;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * Created by wxnacy on 2015/11/30.
 */
public class FileTypeTools extends BaseTools {
    private static final long serialVersionUID = -3188636676846035526L;
    private static final int byteSize = 28;

    public static String getType(String filePath) throws IOException{
        Path path = Paths.get(filePath);
        try(InputStream is = Files.newInputStream(path, StandardOpenOption.READ);
            BufferedInputStream bis = new BufferedInputStream(is);) {
            return getType(bis);
        }catch (IOException e){
            throw new IOException(e);
        }
    }

    public static String getType(InputStream is) throws IOException{
        byte[] bytes = new byte[byteSize];
        is.read(bytes);
        String byteString = StringTools.bytesToHexString(bytes);
        for(FileTypeEnum fileType:FileTypeEnum.values()){
            String key = fileType.getKey();
            if(byteString.startsWith(key)){
                return fileType.getValue();
            }
        }
        return null;
    }


}
